import { IProtocol } from "../IProtocol";
import { IBusinessHandler } from "../../Util/IBusinessHandler";
import { IIOHandler } from "../../Util/IIOHandler";
import { SerializeStream } from "../../Serialize/SerializeStream";
import ByteArray = require("bytearray-node");
type int = number;
//class GroupProtocol

export class GroupProtocol implements IProtocol, IBusinessHandler {
  constructor(arg1: IProtocol) {
    this._buttonProtocol = arg1;
    return;
  }

  public handleData(
    buf: ByteArray,
    business_handler: IBusinessHandler,
    io_handler: IIOHandler,
    business_handler2: IBusinessHandler
  ): int {
    return this._buttonProtocol.handleData(
      buf,
      this,
      io_handler,
      business_handler
    );
  }

  public handlePacket(
    bytes_data: ByteArray,
    handler: IBusinessHandler
  ): Boolean {
    var len_temp = 0;
    var len = 0;
    while (bytes_data.position < bytes_data.length) {
      len_temp = bytes_data.readUnsignedByte();
      if (len_temp != 255) {
        len = len_temp;
      } else {
        len = bytes_data.readUnsignedInt();
      }
      let bytes = new ByteArray();
      bytes.endian = "LE";
      bytes_data.readBytes(bytes, 0, len);
      handler.handlePacket(bytes, null);
    }
    return true;
  }

  /**
   * 将数据写入流，并发送
   * @param bytes_data
   * @param handler
   * @return
   */
  public sendDataEncrypt(bytes_data: ByteArray, handler: IIOHandler): Boolean {
    var stream = new SerializeStream();
    stream.writeSize(bytes_data.length);
    stream.byteArray.writeBytes(bytes_data, 0, bytes_data.length);
    stream.byteArray.position = 0;
    return this._buttonProtocol.sendDataEncrypt(stream.byteArray, handler);
  }

  public clear(): void {
    if (this._buttonProtocol) {
      this._buttonProtocol.clear();
    }
    return;
  }

  public get buttonProtocol(): IProtocol {
    return this._buttonProtocol;
  }

  public set buttonProtocol(arg1: IProtocol) {
    this._buttonProtocol = arg1;
    return;
  }

  private _buttonProtocol: IProtocol;
}
